package com.google.project.client.Director;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.ListBox;

public class DRTHumanReq extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided=true) CellTable<ProjectDTO> ctbProjectList = new CellTable<ProjectDTO>();
	@UiField Button searchBtn;
	@UiField SimplePager pager;
	@UiField TextBox txtPJCode;
	@UiField TextBox txtPJName;
	@UiField ListBox hmReqStatus;
	
	private final ProjectServiceAsync projService = GWT.create(ProjectService.class);
	List<ProjectDTO> list = new ArrayList<ProjectDTO>();
	
	private int hmReq;
	interface Binder extends UiBinder<Widget, DRTHumanReq> {
	}
	
	public DRTHumanReq() {
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			public void execute() {
				txtPJCode.setFocus(true);
			}
		});
		fillCbStatus();
		initTable();
		bindData();	//du an
	}
	
	public DRTHumanReq(int _hmReqStatus) {
		this.hmReq = _hmReqStatus;
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			public void execute() {
				txtPJCode.setFocus(true);
			}
		});
		fillCbStatus(hmReq);
		initTable();
		searchFunction(hmReq);
	}

	public void fillCbStatus() {
		hmReqStatus.addItem("---Tất cả---", "0");
		hmReqStatus.addItem("Chưa phê duyệt", "1");
		hmReqStatus.addItem("Đã phê duyệt", "2");
		hmReqStatus.setSelectedIndex(0);
	}
	
	public void fillCbStatus(int status) {
		hmReqStatus.addItem("---Tất cả---", "0");
		hmReqStatus.addItem("Chưa phê duyệt", "1");
		hmReqStatus.addItem("Đã phê duyệt", "2");
		hmReqStatus.setSelectedIndex(status);
	}
	
	public void bindData() {
		try {
			projService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {
				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(List<ProjectDTO> result) {
					for (ProjectDTO projectDTO : result) {
						if(projectDTO.getIsReq() !=0){
							list.add(projectDTO);
						}
					}
					loadData(list);
				}
			});
		} catch (Exception ex) {
			ex.getMessage();
		}
	}
	
	public void loadData(List<ProjectDTO> projectList) {
		// Create a data provider.
		ListDataProvider<ProjectDTO> dataProvider = new ListDataProvider<ProjectDTO>();

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index=1;
		List<ProjectDTO> list = dataProvider.getList();
		for (ProjectDTO projectDTO : projectList) {
			projectDTO.setIndex(index);
			list.add(projectDTO);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbProjectList);
		pager.setPageSize(5);
		
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectList);
	}
	
	public void initTable() {
		//STT
		TextColumn<ProjectDTO> indexColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getIndex() + "";
			}
		};


		//Ma du an projectCodeColumn
		Column<ProjectDTO, String> projectCodeColumn = new Column<ProjectDTO, String>(new ClickableTextCell()) {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectCode();
			}
		};
		
		projectCodeColumn.setFieldUpdater(new FieldUpdater<ProjectDTO, String>() {
			@Override
			public void update(int index, ProjectDTO projectDTO, String value) {
				DRTEntrypoint.get().DRTHumanReqDetail(projectDTO);
			}
		});
		
		//Ten du an
		TextColumn<ProjectDTO> projectNameColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectName();
			}
		};

		//So luong nhan vien yeu cau
		TextColumn<ProjectDTO> numberOfHMReqColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				int num=object.getNumOfEmpReq() +object.getNumOfOPT();
				return num+ " (Người)";
			}
		};
		
		//Ngay bat dau du an
		TextColumn<ProjectDTO> startDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project.getStartDate()));
			}
		};
		
		//Ngay ket thuc du an
		TextColumn<ProjectDTO> dueDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project.getDueDate()));
			}
		};
		
		//Phe duyet
		TextColumn<ProjectDTO> exceptedColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				int excepted = project.getIsReq();
				String str = "";
				if(excepted == 1) {
					str += "Chưa phê duyệt";
				} else if(excepted == 2 || excepted==3 || excepted==4) {
					str += "Đã phê duyệt";
				}
				return str;
			}
		};

		ctbProjectList.setWidth("100%", true);
		ctbProjectList.setPageSize(5);
		ctbProjectList.setPageStart(0);
		ctbProjectList.setStyleName("ttable");
		ctbProjectList.addColumn(indexColumn, "STT");
		ctbProjectList.setColumnWidth(indexColumn, 45.0, Unit.PX);
		ctbProjectList.addColumn(projectCodeColumn, "Mã dự án");
		ctbProjectList.setColumnWidth(projectCodeColumn, 15.0, Unit.PCT);
		projectCodeColumn.setCellStyleNames("celltable");
		ctbProjectList.addColumn(projectNameColumn, "Tên dự án");
		ctbProjectList.setColumnWidth(projectNameColumn, 20.0, Unit.PCT);
		projectNameColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		ctbProjectList.addColumn(numberOfHMReqColumn, "Số lượng");
		ctbProjectList.setColumnWidth(numberOfHMReqColumn, 15.0, Unit.PCT);
		numberOfHMReqColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		ctbProjectList.addColumn(startDateColumn, "Ngày bắt đầu");
		ctbProjectList.setColumnWidth(startDateColumn, 13.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(startDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		ctbProjectList.addColumn(dueDateColumn, "Ngày kết thúc");
		ctbProjectList.setColumnWidth(dueDateColumn, 13.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(dueDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		ctbProjectList.addColumn(exceptedColumn, "Tình trạng");
		ctbProjectList.setColumnWidth(exceptedColumn, 13.0, Unit.PCT);
	}
	@UiHandler("searchBtn")
	void onSearchBtnClick(ClickEvent event) {
		searchFunction();
	}
	
	private void searchFunction() {
		List<ProjectDTO> temp = new ArrayList<ProjectDTO>();
		String projectCode = txtPJCode.getText().trim();
		String projectName = txtPJName.getText().trim();
		int index = -1;
		Boolean condition = true;
		for(ProjectDTO project : list) {
			if(projectCode != null){
				condition = condition && (project.getProjectCode().contains(projectCode));
			}
			if(projectName != null){
				condition = condition && (project.getProjectName().contains(projectName));
			}
			if((hmReqStatus.getValue(hmReqStatus.getSelectedIndex()) != null) && (!hmReqStatus.getValue(hmReqStatus.getSelectedIndex()).equalsIgnoreCase("0"))) {
				//condition = condition && (project.getIsReq() == _status);
				 index=Integer.parseInt(hmReqStatus.getValue(hmReqStatus.getSelectedIndex()));
				if(index==1){
					condition = condition && (project.getIsReq() == 1);
				}else if(index==2){
					condition = condition && (project.getIsReq() == 2 ||project.getIsReq() == 3  || project.getIsReq() == 4 ) ;
				}
			}
			if(condition && project.getIsReq() != 0){
				temp.add(project);
			}
			condition = true;
		}
		loadData(temp);
	}
	
	private void searchFunction(final int hmRStatus) {
		final List<ProjectDTO> hmReqList1 = new ArrayList<ProjectDTO>();
		final List<ProjectDTO> hmReqList2 = new ArrayList<ProjectDTO>();
		final List<ProjectDTO> hmReqList3 = new ArrayList<ProjectDTO>();
		projService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				for(ProjectDTO pj : result) {
					list.add(pj);
					if(hmRStatus==1) {
						if(pj.getIsReq()==1){
						hmReqList1.add(pj);
						}else if(hmRStatus==2){
							if(pj.getIsReq()==2 || pj.getIsReq()==3 || pj.getIsReq()==4){
								hmReqList2.add(pj);
							}
						}else if(hmRStatus==0){
							if(pj.getIsReq()==1|| pj.getIsReq()==2 || pj.getIsReq()==3 || pj.getIsReq()==4){
								hmReqList3.add(pj);
							}
						}
					}
				}
				if(hmRStatus==0){
					loadData(hmReqList3);
				}
				else if(hmRStatus==1){
					loadData(hmReqList1);
				}else if(hmRStatus==2){
					loadData(hmReqList2);
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Tải thông tin!");
			}
		});
	}
}
